package com.xzcedu.jdbc.utils;

import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author 徐州城
 * @version 1.0
 * 演示JDBCUtils使用，完成dml 和 select
 */
public class JDBCUtils_Use {

    @Test
    @SuppressWarnings("all")
    public void testSelect(){
        //1. 得到连接
        Connection connection = null;

        //2. 组织sql语句
        String sql = "select * from actor";

        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JDBCUtils.getConnection();
            //class com.mysql.jdbc.JDBC4Connection
            System.out.println(connection.getClass());
            preparedStatement = connection.prepareStatement(sql);
            //执行
            resultSet = preparedStatement.executeQuery();

            //遍历结果集
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date borndate = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex + "\t" + borndate + "\t" + phone);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            JDBCUtils.close(resultSet, preparedStatement, connection);
        }
    }

    @Test
    public void testDML() {

        //1. 得到连接
        Connection connection = null;

        //2. 组织sql语句
        String sql = "update actor set name = ? where id = ?";

        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            //给占位符赋值
            preparedStatement.setString(1, "周星驰");
            preparedStatement.setInt(2, 2);
            //执行
            int rows = preparedStatement.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            JDBCUtils.close(null, preparedStatement, connection);
        }
    }
}
